package cn.zwx.base.utils;


import cn.zwx.base.enums.ResponseCodeEnum;
import cn.zwx.base.exception.BizWrapException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author zhangwenxue
 */
public class ValidationUtils {

    private static final ValidationUtils INSTANCE = new ValidationUtils();
    private final Validator validator;

    private ValidationUtils() {
        this.validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static ValidationUtils getInstance(){
        return INSTANCE;
    }
    public  <T> void validate(T object) throws BizWrapException {
        Set<ConstraintViolation<T>> violations = INSTANCE.validator.validate(object);
        if (!violations.isEmpty()) {
            throw new BizWrapException(ResponseCodeEnum.PARAMS_VALID_ERROR.getCode(),violations.iterator().next().getMessage());
        }
    }
}
